package com.hzz.service.eybase;

import com.hzz.api.eybase.IEyBaseRetrieveHydlService;
import com.hzz.dao.eybase.IEyBaseRetrieveReachDao;
import com.hzz.dao.eybase.IEyBaseRetrieveRiversDao;
import com.hzz.dto.eybase.EyBaseRetrieveHydlDto;
import com.hzz.entity.eybase.EyBaseRetrieveHydl;
import com.hzz.framework.Response;
import com.hzz.framework.SysErrorCode;
import com.hzz.framework.annotation.FeignService;
import com.hzz.framework.exception.ServiceException;
import com.hzz.framework.service.BaseService;
import com.hzz.framework.util.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@FeignService
@Slf4j
public class EyBaseRetrieveHydlService extends BaseService implements IEyBaseRetrieveHydlService {
    @Autowired
    IEyBaseRetrieveRiversDao retrieveRiversDao;
    @Autowired
    IEyBaseRetrieveReachDao retrieveReachDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = CommonConstant.DB_DEFAULT_TIMEOUT, rollbackFor = {Exception.class, RuntimeException.class})
    public Response saveOrUpdateData(String type, EyBaseRetrieveHydlDto dto) throws Exception {
        Response result = new Response(0, "success");
        try {
            EyBaseRetrieveHydl entity = copyTo(dto, EyBaseRetrieveHydl.class);
            if ("rivers".equalsIgnoreCase(type)) {
                //判断数据是否存在
                if (retrieveRiversDao.isDataExist(entity) != 0) {
                    //数据存在
                    retrieveRiversDao.update(entity);
                } else {
                    //新增
                    retrieveRiversDao.insert(entity);
                    result.data = entity.getGid();
                }
            } else {
                //判断数据是否存在
                if (retrieveReachDao.isDataExist(entity) != 0) {
                    //数据存在
                    retrieveReachDao.update(entity);
                } else {
                    //新增
                    retrieveReachDao.insert(entity);
                    result.data = entity.getGid();
                }
            }
        } catch (Exception e) {
            log.error("信息保存异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return result;
    }

    @Override
    public int deleteByExpireDay(String type, Integer expireDay){
        try {
            if ("rivers".equalsIgnoreCase(type)) {
                return retrieveRiversDao.deleteByExpireDay(expireDay);
            } else {
                return retrieveReachDao.deleteByExpireDay(expireDay);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
